package com.gx.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gx.common.anntation.Log;
import com.gx.common.exception.FileUploadException;
import com.gx.common.result.AppResult;
import com.gx.model.dto.QueryMediaParamsDto;
import com.gx.model.dto.UploadFileParamsDto;
import com.gx.model.po.TbFiles;
import com.gx.model.result.UploadFileResultDto;
import com.gx.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Author Liu-pj
 * @Date 2023/3/8 10:47
 * @Desc 文件管理接口
 **/
@Api(tags = "普通文件上传")
@RestController
public class FilesController {
    @Autowired
    FileService fileService;

    @ApiOperation("列表查询接口")
    @PostMapping("/files")
    @Log(description = "文件操作", type = "列表查询接口")
    public Page<TbFiles> list(@RequestBody QueryMediaParamsDto queryMediaParamsDto) {
        return fileService.queryMediaFiles(queryMediaParamsDto);
    }

    @ApiOperation(value = "文件上传")
    @PostMapping(value = "/upload/courseFile")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "folder", value = "桶下边子目录", dataTypeClass = String.class),
            @ApiImplicitParam(name = "objectName", value = "对象名称", dataTypeClass = String.class)
    })
    @Log(description = "文件操作", type = "普通文件上传")
    public UploadFileResultDto upload(@RequestPart("file") MultipartFile file,
                                      @RequestParam(value = "folder", required = false) String folder,
                                      @RequestParam(value = "objectName", required = false) String objectName) {
        UploadFileParamsDto uploadFileParamsDto = new UploadFileParamsDto();
        String contentType = file.getContentType();
        uploadFileParamsDto.setContentType(contentType);
        uploadFileParamsDto.setFileSize(file.getSize());
        uploadFileParamsDto.setFileName(file.getOriginalFilename());
        UploadFileResultDto uploadFileResultDto = null;
        try {
            uploadFileResultDto = fileService.uploadFile(uploadFileParamsDto, file.getBytes(), folder, objectName);
        } catch (Exception e) {
            FileUploadException.cast("上传文件过程中出错");
        }
        return uploadFileResultDto;

    }

    @ApiOperation("预览文件")
    @GetMapping("/preview/{id}")
    @ApiImplicitParam(name = "id", value = "文件id", dataTypeClass = String.class)
    public AppResult<String> getPlayUrlByMediaId(@PathVariable String id) {
        //调用service查询文件的url
        TbFiles tbFiles = fileService.getFileById(id);
        return AppResult.success(tbFiles.getUrl());
    }

}
